package com.zyl.blog.common.enums;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.core.enums
 * @ClassName: OpenStatus
 * @Description
 * @Author FinalFantasy
 * @Date 2025/2/17-20:28
 */
@Getter
@AllArgsConstructor
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum OpenStatus {

    ENABLED(1, "开启"),
    DISABLED(0, "关闭"),
    MAINTENANCE(2, "维护中"),
    SCHEDULED(3, "计划开放"),
    SUCCESS(200, "成功" ),
    BIZ_FAIL(500, "业务失败"),
    SYS_FAIL(501, "系统失败");

    /**
     * 数据库存储值
     */
    @JsonValue  // 控制JSON序列化输出值
    private final Integer code;

    /**
     * 状态描述
     */
    private final String desc;

    private static final Map<Integer, OpenStatus> CODE_MAP = Arrays.stream(values())
            .collect(Collectors.toMap(OpenStatus::getCode, Function.identity()));

    /**
     * 根据编码获取枚举实例
     *
     * @throws IllegalArgumentException 当传入无效编码时抛出业务异常
     */
    public static OpenStatus fromCode(Integer code) {
        OpenStatus status = CODE_MAP.get(code);
        if (status == null) {
            throw new IllegalArgumentException("无效的开放状态编码: " + code);
        }
        return status;
    }
}